<?php
namespace app\api\controller;

use \think\Request;
use \think\Db;
use think\Session;
use think\Config;
use think\Controller;
use ucpaas\SendMsg;

class My extends Base
{
    /**
     * @writer:leijie
     * @DateTime:2018-01-17
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---设置首页
     * @return array|Json
     */
    public function info(){
        $data = input();//Request::instance()->post();
        if (!empty($data['id'])){
            $userId = $data['id'];
            $re = Db::name('user')
                ->alias('U')
                ->where(['U.id'=>$userId])
                ->where(['C.comment_type'=>'1'])
                ->join('comment C','C.user_id = U.id','left')
                ->join('supplier S','S.id = C.supplier_id','left')
                ->field("C.*,DATE_FORMAT(C.time,'%a')as day,S.image")
                ->field("case DATE_FORMAT(C.time,'%w') when 0 then '周日' when 1 then '周一' when 2 then '周二' when 3 then '周三' when 4 then '周四' when 5 then '周五' when 6 then '周六' end as day_CN ")
                ->order('C.time desc')
                ->limit(5)
                ->group('C.order_id')
                ->select();
            if ($re !== false){
                $result = Config::get('code.success');
                $result['count'] = count($re);
                $result['data'] = $re;
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-17
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---收到的评价
     * @return array|Json
     */
    public function comment(){
        // 商户对用户的评价
        $data = Request::instance()->post();
        if (!empty($data['id']) && !empty($data['type']) && !empty($data['page_no'])){
            $userId = $data['id'];
            $type = $data['type'];
            $pageNo = $data['page_no'];
            $pageSize = 6;
            switch ($type){
                case '1':
                    $where = '';
                    $order = 'C.time desc';
                    break;
                case '2':
                    $where = 'C.star<3';
                    $order = 'C.star desc';
                    break;
                case '3':
                    $where = '';
                    $order = 'C.time desc';
                    break;
                default:
                    $result = Config::get('code.mistake');
                    $result['msg'] = '参数错误';
                    return json($result);
                    break;
            }
            $re = Db::name('comment')
                ->alias('C')
                ->where(['C.user_id'=>$userId])
                ->where($where)
                ->where('C.comment_type',1)
                ->join('supplier S','S.id = C.supplier_id','left')
                ->field('DATE_FORMAT(C.time,\'%Y/%m/%d\')as day,C.comment,C.star,S.image,S.name,S.address')
                ->order($order)
                ->group('C.order_id')
                ->limit(($pageNo-1)*$pageSize,$pageSize)
                ->select();
            $sum = Db::name('comment')
                ->alias('C')
                ->where(['C.user_id'=>$userId])
                ->where($where)
                ->where('C.comment_type',1)
                ->group('C.order_id')
                ->count();
            if ($re){
                $result = Config::get('code.success');
                $result['count'] =count($re);
                $result['type'] = $type;
                $result['data'] = $re;
            }else{
                $result = Config::get('code.null');
            }
            $result['total'] =$sum;
            return json($result);
        }else{
            $result = Config::get('code.miss');
            return json($result);
        }
    }


    /**
     * @writer:leijie
     * @DateTime:2018-01-19
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---系统通知---订单状态
     * @return array|Json
     */
    public function orderSystem(){
        $data = Request::instance()->post();

        if (!empty($data['id']) && !empty($data['page_no'])){
            $userId = $data['id'];
            $pageNo = $data['page_no'];
            $pageSize = 4;
            // 订单状态为已收货，收货时间排序
            $re = Db::name('notice')
                ->alias('N')
                ->join('order O','N.notice_read_id = O.id','left')
                ->where('N.user_id',$userId)
                ->where('N.notice_type',1)
                ->where('N.show_type',1)
                ->field("O.*,N.title,case DATE_FORMAT(N.create_time,'%w') when 0 then '周日' when 1 then '周一' when 2 then '周二' when 3 then '周三' when 4 then '周四' when 5 then '周五' when 6 then '周六' end as week ,DATE_FORMAT(N.create_time,'%a')as day,DATE_FORMAT(N.`create_time`,'%H:%i') as hour")
                ->limit(($pageNo-1)*$pageSize,$pageSize)
                ->order('N.id desc')
                ->select();
                $result = Config::get('code.success');
                $result['count'] = count($re);
            if ($re){
                foreach ($re as $key =>$value){
                    $orderInfo = Db::name('order_info')
                        ->alias('OI')
//                        ->where('OI.is_give','0')
                        ->join('product P','OI.product_id = P.id','left')
                        ->field('P.image,P.name,OI.specification_name,OI.packing_proportion,format(OI.price,2) as price,OI.num')
                        ->where(['order_id'=>$value['id']])
                        ->select();
                        if($orderInfo){
                            $result['data'][$key] = $value;
                            $result['data'][$key]['goods'] = $orderInfo;
                        }else{
                            $result = Config::get('code.error');
                        }
                }
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-03-01
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的订单---待发货---提醒发货
     * @return array|Json
     */
    public function remindDelivery(){
        $post = Request::instance()->post();
        if (!empty($post['order_id'])) {
            $orderId    = $post['order_id'];
            $order      = Db::table('order')->where('id',$orderId)->find();
            if ($order['is_remind'] == 0){
                $arr = [];
                $arr['supplier_id']     = $order['supplier_id'];
                $arr['user_id']         = $order['user_id'];
                $arr['title']           = '用户提醒发货';
                $arr['title_english']   = 'user reminding shipments';
                $arr['content']         = $order['order_no'].'该订单用户提醒发货';
                $arr['content_english'] = $order['order_no'].'the order user reminding the shipper';
                $arr['create_time']     = date("Y-m-d H:i:s", time());
                $arr['notice_type']     = 1;
                $arr['show_type']       = 2;
                $res = Db::table('notice')->insert($arr);
                if ($res){
                    $notice_id = Db::table('notice')->getLastInsID();
                    $info = [];
                    $info['user_id']    = $order['user_id'];
                    $info['status']     = 'nul';
                    $info['type']       = 1;
                    $info['notice_id']  = $notice_id;
                    Db::table('notice_read')->insert($info);
                    $notice_read_id = Db::table('notice_read')->getLastInsID();
                    Db::table('notice')->where('id',$notice_id)->setField('notice_read_id',$notice_read_id);
                    $re      = Db::name('order')
                        ->where(['id' => $orderId])
                        ->setField('is_remind', 1);
                    if ($re) {
                        $result = Config::get('code.success');
                    } else {
                        $result        = Config::get('code.error');
                        $result['msg'] = '提醒发货失败,请勿重复提醒！';
                    }
                }else{
                    $result        = Config::get('code.error');
                    $result['msg'] = '提醒发货失败,请重新提醒！';
                    return json($result);
                }
            }else{
                $result        = Config::get('code.error');
                $result['msg'] = '提醒发货失败,请勿重复提醒！';
                return json($result);
            }
        } else {
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-19
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---系统通知---商家推广
     * @return array|Json
     */
    public function shopSystem(){
        $data = Request::instance()->post();
        if (!empty($data['id']) && !empty($data['page_no'])){
            $userId =$data['id'];
            $type = 2;
            $pageNo = $data['page_no'];
            $pageSize = 4;
            // 找出所有类型为'推广'的,并向商家配送区域的用户推送
            $re = Db::name('notice')
                ->alias('N')
                ->where('N.notice_type',$type)
                ->where("FIND_IN_SET($userId,user_id)")
                ->join('supplier S','S.id = N.supplier_id','left')
                ->field('N.supplier_id,N.supplier_name,S.image')
                ->limit(($pageNo-1)*$pageSize,$pageSize)
                ->order('create_time')
                ->select();
            if ($re){
                $result = Config::get('code.success');
                $result['count']= count($re);
                $result['data']= $re;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-19
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---系统通知---通知
     * @return array|Json
     */
    public function noticeSystem(){
        $data = Request::instance()->post();
        if (!empty($data['user_id']) && !empty($data['page_no'])){
            $userId =$data['user_id'];
            $type = 3;
            $pageNo = $data['page_no'];
            $pageSize = 4;
            // 找出所有类型为'通知'的,并是给当前用户推送的
            $re = Db::name('notice')
                ->alias('N')
                ->join('supplier S','S.id = N.supplier_id','left')
                ->where('N.notice_type',$type)
                ->where('N.show_type',1)
//                ->where("FIND_IN_SET($userId,N.user_id)")
                ->field('N.title,N.outline,N.content,S.image,case DATE_FORMAT(create_time,\'%w\') when 0 then \'周日\' when 1 then \'周一\' when 2 then \'周二\' when 3 then \'周三\' when 4 then \'周四\' when 5 then \'周五\' when 6 then \'周六\' end as week ,DATE_FORMAT(create_time,\'%a\')as day,N.id as notice_id,DATE_FORMAT(`create_time`,\'%H:%i\') as hour')
                ->limit(($pageNo-1)*$pageSize,$pageSize)
                ->order('N.create_time')
                ->select();
            if ($re){
                $result = Config::get('code.success');
                $result['count']= count($re);
                $result['data']= $re;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-18
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---我的账号
     * @return array|Json
     */
    public function myAccount(){
        $data = Request::instance()->post();
        if (!empty($data['id'])){
            $userId = $data['id'];
            $re = Db::name('user')
                ->field('name,image,phone,account')
                ->where(['id'=>$userId])
                ->find();
            if ($re){
                $result = Config::get('code.success');
                $result['data'] = $re;
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-18
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---修改头像
     * @return array|Json
     */
    public function imgEdit(){
        $data = Request::instance()->post();
        if (!empty($data['id']) && !empty($data['image'])){
            $userId = $data['id'];
            $re = Db::name('user')
                ->where(['id'=>$userId])
                ->setField(['image'=>$data['name']]);
            if (false !== $re){
                $result = Config::get('code.success');
                $result['data'] = $re;
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-18
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---修改用户名
     * @return array|Json
     */
    public function usernameEdit(){
        $data = Request::instance()->post();
        if (!empty($data['id']) && !empty($data['name'])){
            $userId = $data['id'];
            $re = Db::name('user')
                ->where(['id'=>$userId])
                ->setField(['name'=>$data['name']]);
            if (false !== $re){
                $result = Config::get('code.success');
                $result['data'] = $re;
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-18
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---修改用户密码
     * @return array|Json
     */
    public function passwordEdit(){
        $data = Request::instance()->post();
        if (!empty($data['id']) &&!empty($data['password'])){
            $userId = $data['id'];
            // 加密密码
            $data['password'] = md5($data['password']);
            $re = Db::name('user')
                ->where(['id'=>$userId])
                ->setField('password',$data['password']);
            if (false !== $re){
                $result = Config::get('code.success');
                $result['data'] = $re;
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }
    /**
     * @writer:leijie
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---功能介绍
     * @return array|Json
     */
    public function keyFeatures(){
        try {
            $re = Db::name('protocol')
                ->where(['type'=>3])
                ->order('id desc')
                ->find();
            if (false !== $re){
                $result = Config::get('code.success');
                $result['data'] = $re;
            }else{
                $result = Config::get('code.error');
            }
        } catch(Exception $e) {
            $result = Config::get('code.default');
        }

        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-18
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---发送短信接口
     * @return array|Json
     */
    public function codeGet(){
        $data = Request::instance()->post();
        if (!empty($data['account'])){
            $account = $data['account'];
            $code = codeRange(6);
            // 发送短信
            $msmRes = json_decode(SendMsg($account,$code),true);
            if ('000000' !== $msmRes['code']){
                // 发送失败
                $result = Config::get('code.error');
                $result['msg'] = "发送失败";
            }else{
                // 验证码存session
                Session::set('code',$code);
                Session::set('tel',$account);
                $result = Config::get('code.success');
                $result['data']['code'] = $code;
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-18
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---短信修改手机号码
     * @return array|Json
     */
    public function accountEdit(){
        // 修改登录账号的手机号码
        $data = Request::instance()->post();
        if (!empty($data['id']) && !empty($data['account']) && !empty($data['code'])){
            $userId = $data['id'];
            $account = $data['account'];
            $code = $data['code'];
            // 判断新手机号和原手机是否一样
            $oldAccount = Db::name('user')
                ->where(['id'=>$userId])
                ->field('account')
                ->find();
            if ($account == $oldAccount['account']){
                $result = Config::get('code.error');
                $result['msg'] = "新手机号和原手机号一样";
                return json($result);
            }
            // 判断新手机号数据库是否存在
            $checkAccount = Db::name('user')
                ->where(['account'=>$account])
                ->field('id,name,account')
                ->select();
            if ($checkAccount){
                $result = Config::get('code.error');
                $result['msg'] = "手机号已在用户端注册";
                return json($result);
            }
            $supplier = Db::name('supplier')
                ->where(['account'=>$account])
                ->field('id,name,account')
                ->select();
            if($supplier){
                $result = Config::get('code.error');
                $result['msg'] = "手机号已在商户端注册";
                return json($result);
            }
            // 获取短信验证码
            $sendCode = Session::get('code');
            $sendPhone = Session::get('tel');
            // 验证短信验证码
            if ($sendCode == $code && $sendPhone == $data['account']){
                $re = Db::name('user')
                    ->where(['id'=>$userId])
                    ->setField('account',$data['account']);
                if ($re){
                    $result = Config::get('code.success');
                    $result['data'] = $re;
                }else{
                    $result = Config::get('code.error');
                }
            }else{
                $result = Config::get('code.error');
                $result['msg'] = "验证码错误";
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }
}